package com.fbli.test.config;

import com.fbli.test.common.result.ResultSend;
import com.fbli.test.util.JsonUtil;
import com.fbli.test.util.StringUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomFilter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = getToken(request);
        return new CustomToken(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {
        if (((HttpServletRequest) servletRequest).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //校验身份
        //第一步：获取token
        String token = getToken(httpServletRequest);
        //第二步：判断token是否为空
        if (StringUtil.isNull(token)) {  //说明身份是非法的
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.getWriter().write(JsonUtil.INSTANCE.obj2json(ResultSend.send(100006, "请求错误！", null)));
            return false;
        }
        //当前的方法返回true才放行  否则这个程序也就执行到这里了....
        return executeLogin(servletRequest, servletResponse);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            httpResponse.getWriter().write(throwable.getMessage());
        } catch (IOException e1) {

        }

        return false;
    }

    private String getToken(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("Authorization"); // 从头部获取
        if (StringUtil.isNull(token)) token = httpServletRequest.getParameter("token"); // 从参数中获取
        return token;
    }

}
